const {Script} = require("vm");
const {browser} = require('../../');
const jsdom = require('sdenv-jsdom');
const cheerio = require('cheerio');
const logger = require("../../utils/logger");
const {jsdomFromTextWithCookie} = require("./index");
const {CookieJar} = jsdom;


function func_rs(url, htmltext, jstext, cookie_obj, res, startTime) {
    const url_obj = new URL(url);
    const baseUrl = url_obj.protocol + '//' + url_obj.hostname;
    let defaultCookieJar = new CookieJar();
    let cookie_str = '';
    Object.keys(cookie_obj).forEach(key => {
        cookie_str += `${key}=${cookie_obj[key]}; `
    });
    if (cookie_str) {
        defaultCookieJar.setCookieSync(cookie_str, baseUrl);
    }
    const [jsdomer, cookieJar] = jsdomFromTextWithCookie({
        url: `${url}`,
        referrer: `${url}`,
        contentType: "text/html",
        runScripts: "outside-only",
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
    }, defaultCookieJar);
    const dom = jsdomer(htmltext);

    const $ = cheerio.load(htmltext);
    const scripts = [...$('script')]
    const tsscript = scripts.map(ele => $(ele).text()).filter(text => text.includes('$_ts.nsd') && text.includes('$_ts.cd'));
    let window = dom.window;
    window.$_ts = Function('window', tsscript[0] + 'return $_ts')({});
    window.onbeforeunload = async (url) => {
        const cookies_str = cookieJar.getCookieStringSync(baseUrl);
        let cookies = cookies_str.split('; ').reduce((acc, cur) => {
            const [key, value] = cur.split('=');
            acc[key] = value;
            return acc;
        }, {});
        logger.info(`生成cookie(${new Date().getTime() - startTime}ms):`, cookies);
        window.close();
        if (res) {
            res.status(200).json({
                "code": 200,
                "data": cookies,
                "cost": `${new Date().getTime() - startTime}ms`,
                "msg": "调用成功"
            })
        }
    }
    browser(window, 'chrome');
    new Script(jstext).runInContext(dom.getInternalVMContext());
};


module.exports = func_rs;